package cetcbigdata.da.base;

import java.io.*;
import java.net.InetAddress;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.alibaba.fastjson.JSONObject;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author YuanGongPing
 * @version 0.1
 * @description Js
 * @since 2022/8/3 17:28
 */
public class DownloadAndUploadMinio {
    public  static  String minioIp = "172.10.10.185";
    public Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 最大线程池
     */
    public static final int THREAD_POOL_SIZE = 8;

    public static  MinioClient minioClient;


    public interface HttpClientDownLoadProgress {
        public void onProgress(int progress);
    }

    private static DownloadAndUploadMinio httpClientDownload;

    private ExecutorService downloadExcutorService;

    private DownloadAndUploadMinio() {
        minioClient =  MinioClient.builder()
                .endpoint("http://172.16.119.5:9000")
                .credentials("minio", "minio123")
                .build();

        downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    }

    public static DownloadAndUploadMinio getInstance() {
        if (httpClientDownload == null) {
            httpClientDownload = new DownloadAndUploadMinio();
        }
        return httpClientDownload;
    }

    private static void cteateBucket(String bucketName) throws Exception{
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    public String uploadFileToMinio(InputStream inputStream, String bucketName, String fileName ) throws Exception {
        // 检查bucket 是否存在， 如果不存在则创建
        cteateBucket(bucketName);
        assert fileName != null;
        Map<String, String> userMetadata = new HashMap<>();
        userMetadata.put("originalfilename", fileName);

        String[] strArray = fileName.split("\\.");
        int suffixIndex = strArray.length - 1;
        // 新的文件名 = uuid + 文件后缀
        String uuidFileName =  UUID.randomUUID().toString() + "." + strArray[suffixIndex];
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(uuidFileName)
                        .stream(inputStream, -1, 10485760)
                        .userMetadata(userMetadata)
                        .build()
        );
        return uuidFileName;
    }


    public String downloadPost( String url,  JSONObject headers, JSONObject params, String fileName) {
        String id = null;
        InputStream out = null;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        // 创建httpClient实例
        httpClient = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        // 配置请求参数实例
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                .setSocketTimeout(60000)// 设置读取数据连接超时时间
                .build();
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        /**********   设置请求头        **********/
        if(null != headers && headers.size() > 0 ){
            Set<Map.Entry<String, Object>> entrySet = headers.entrySet();
            // 循环遍历，获取迭代器
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = iterator.next();
                httpPost.addHeader(mapEntry.getKey(), mapEntry.getValue().toString());
            }
        }
        /**********      封装post请求参数    **********/
        if (null != params && params.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 通过map集成entrySet方法获取entity
            Set<Map.Entry<String, Object>> entrySet = params.entrySet();
            // 循环遍历，获取迭代器
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }
            // 为httpPost设置封装好的请求参数
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();
            out = entity.getContent();
            // 是文件服务器ip 则上传，非debug
            if(minioIp.equals(InetAddress.getLocalHost().getHostAddress()) ){
                id = uploadFileToMinio(out, "chengdu", fileName);
            }else {
                id = fileName;
                logger.info("保存文件：" + id);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return id;
    }


    public String downloadGet(String url, JSONObject headers, JSONObject parmas, String fileName) throws Exception {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String id = "";
        try {
            // 通过址默认配置创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            HttpGet httpGet;
            /*************    请求参数  ***************/
            if (null != parmas && parmas.size() > 0) {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                // 通过map集成entrySet方法获取entity
                Set<Map.Entry<String, Object>> entrySet = parmas.entrySet();
                // 循环遍历，获取迭代器
                Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, Object> mapEntry = iterator.next();
                    nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
                }
                httpGet = new HttpGet(new URIBuilder(url).addParameters(nvps).build());
            }else{
                httpGet = new HttpGet(url);
            }

            // 设置请求头信息
            /**********             设置请求头                          **********/
            if(null != headers && headers.size() > 0 ){
                Set<Map.Entry<String, Object>> entrySet = headers.entrySet();
                // 循环遍历，获取迭代器
                Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, Object> mapEntry = iterator.next();
                    httpGet.addHeader(mapEntry.getKey(), mapEntry.getValue().toString());
                }
            }

            // 设置配置请求参数
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)// 请求超时时间
                    .setSocketTimeout(60000)// 数据读取超时时间
                    .build();
            // 为httpGet实例设置配置
            httpGet.setConfig(requestConfig);
            // 执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            if(minioIp.equals(InetAddress.getLocalHost().getHostAddress()) ){
                id = uploadFileToMinio(entity.getContent(), "chengdu", fileName);
            }else {
                id = fileName;
                logger.info("保存文件：" + id);
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return id;
    }


    //    public static void main(String[] args) throws Exception {
    //        DownloadAndUploadMinio ss = new DownloadAndUploadMinio();
    //        ss.downloadGet("http://zwfw.hubei.gov.cn/web/lcfile/group1/M00/00/DB/wKhUBV1jos2AS4K4AAQ7o1bTn4E712.png", new JSONObject(),
    //                new JSONObject(), "sss.png");
    //    }
}
